/*
 * @Author: kanglang
 * @Date: 2021-04-22 11:39:37
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-04-30 01:12:30
 * @Description: 修理卡核销
 */

import React, { Component } from 'react';
import {
  View,
  SafeAreaView,
  Text,
  TextInput,
  StyleSheet,
  TouchableOpacity,
  Image,
  NativeModules,
  Platform,
  BackHandler,
  ScrollView,
  Keyboard
} from 'react-native';
import { BackImage, Header, msg, Button } from '@/common';
import { iconOilPriceAmount, } from '@/images';
import {
  isAndroid,
  px2dp,
  fontColorBlack,
  fontColorCoffee,
  mainBgColorLightGray,
  mainBgColorWhite,
  splitLineColorLightGray
} from '@/styles';
import api from '@/api';
import WlAddressSelect from '../components/wl-address-select';
import UploadImg from '../components/upload-img';

const { Submit } = Button;

export default class VerificationBill extends Component {
  constructor(props) {
    super(props);
    const { navigation } = props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { data } = params;
    this.state = {
      data: data || [],
      writeOffAmount: '', // 核销金额
      fileList: [],
      remark: '',
      repairStations: [],
      veriCardDetails: {},
      keyboardHeight: 0, // 键盘高度
    };
  }

  componentDidMount() {
    const { data } = this.state;
    this.getRepairList();
    api.repair.verificationTime({
      maintenanceNo: data[1],
      time: data[2],
    }).then(res => {
      if (res.success) {
        this.getVeriCardDetails();
      } else {
        msg.emit('app:tip', { text: res.msg || '没有核销权限' });
        msg.emit('router: goToNext', {
          routeName: 'Main'
        });
      }
    });
    if (isAndroid) {
      BackHandler.addEventListener('hardwareBackPress', this.androidBack);
    }

    // 监听键盘
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardWillShow',
      this._keyboardDidShow.bind(this),
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardWillHide',
      this._keyboardDidHide.bind(this),
    );
  }

  _keyboardDidShow(e) {
    this.setState({
      keyboardHeight: e.startCoordinates.height,
    });
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0,
    });
  }

  // 获取授权卡详情
  getVeriCardDetails = () => {
    const { data } = this.state;
    api.repair.repairGetAuthById({ id: data[0] }).then(res => {
      if (res.success) {
        const veriCardDetails = res.data;
        console.log('======veriCardDetails=========>', veriCardDetails);
        this.setState({ veriCardDetails });
      }
    });
  }

  // 获取修理点
  getRepairList = () => {
    api.repair.getRepair().then(res => {
      if (res.success) {
        const repairStations = res.data;
        this.setState({ repairStations });
      }
    });
  }

  componentWillUnmount() {
    if (isAndroid) {
      BackHandler.removeEventListener(
        'hardwareBackPress',
        this.androidBack
      );
    }
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  androidBack = () => {
    this.goBack();
    return true;
  }

  render() {
    const { writeOffAmount, fileList, remark, repairStations } = this.state;
    const stations = repairStations.length > 0 ? repairStations[0] : {};
    return (
      <SafeAreaView style={styles.container}>
        {this.renderHead()}
        <ScrollView>
          <View style={{ flex: 1, paddingBottom: Number(this.state.keyboardHeight) + 10 }}>
            <View style={styles.writeOffContainer}>
              <WlAddressSelect
                selfAddressDetails={stations.address}
                selfAddressName={stations.name}
                selfAddressId={stations.id}
                selfAddressLat={stations.la}
                selfAddressLog={stations.lg}
                rightArrow={false}
              />
            </View>
            <View style={styles.writeOffContainer}>
              <View style={styles.writeOffHandleContainer}>
                <View style={styles.writeOffHandleTitle}>
                  <Image
                    style={styles.writeOffHandleImage}
                    source={iconOilPriceAmount}
                  />
                  <Text style={{ color: '#333232', fontSize: px2dp(32) }}>核销金额</Text>
                </View>
                <View style={{ flexDirection: 'row', alignItems: 'center', alignItems: 'flex-end' }}>
                  <Text style={{ color: '#333232', fontSize: px2dp(32), fontWeight: 'bold' }}>¥</Text>
                  <TextInput
                    style={styles.priceInput}
                    value={writeOffAmount}
                    keyboardType='decimal-pad'
                    onChangeText={text => {
                      let newText = text !== '' && text.substr(0, 1) === '.' ? '' : text;
                      newText = newText.replace(
                        /^0+[0-9]+/g,
                        '0'
                      ); // 不能以0开头输入
                      newText = newText.replace(/[^\d.]/g, ''); // 清除"数字"和"."以外的字符
                      newText = newText.replace(/\.{2,}/g, '.'); // 只保留第一个, 清除多余的
                      newText = newText.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3',); // 只能输入两个小数
                      newText = newText
                        .replace('.', '$#$')
                        .replace(/\./g, '')
                        .replace('$#$', '.');
                      let inpValue = this.state.writeOffAmount;
                      if (Number(newText) >= 100000) {
                        inpValue = '100000';
                      } else {
                        inpValue = newText;
                      }
                      this.setState({ writeOffAmount: inpValue });
                    }}
                    placeholder='请输入核销金额'
                  />
                </View>
              </View>
            </View>
            <View style={styles.writeOffContainer}>
              <View style={styles.repairEvidence}>
                <Image
                  style={styles.writeOffHandleImage}
                  source={iconOilPriceAmount}
                />
                <Text style={{ color: '#333232', fontSize: px2dp(32) }}>修理凭证</Text>
              </View>
              <View style={styles.uploadBox}>
                <UploadImg
                  style={{ marginTop: px2dp(20) }}
                  action='upload?dirName=repair'
                  fileList={fileList}
                  limit={3}
                  onChange={(fileList) => {
                    this.setState({ fileList });
                  }}
                />
              </View>
              <View style={styles.inputContent}>
                <Text style={styles.remark}>备注</Text>
                <View style={{
                  flexDirection: 'row',
                  backgroundColor: mainBgColorLightGray,
                  // justifyContent: 'center',
                  paddingLeft: px2dp(14),
                  alignItems: 'flex-start',
                  borderRadius: px2dp(8),
                  marginTop: px2dp(8)
                }}
                >
                  <TextInput
                    style={styles.inputContentTextInput}
                    placeholder='点击可输入备注'
                    placeholderTextColor='#CDCCC9'
                    multiline
                    maxLength={100}
                    value={remark}
                    underlineColorAndroid='transparent'
                    onChangeText={(text) => {
                      this.setState({ remark: text });
                    }}
                    onBlur={() => {
                    }}
                  />
                </View>
              </View>
            </View>
            <View style={styles.btnBox}>
              <Submit
                text='提交'
                boxStyle={styles.boxStyle}
                onClick={() => {
                  this.submitBtn();
                }}
              />
            </View>
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }

  // 自定义头部
  renderHead = () => {
    return (
      <Header
        renderTitle={() => <Text style={styles.headTitleText}>修理卡</Text>}
        renderLeft={() => {
          return (
            <TouchableOpacity
              activeOpacity={0.8}
              onPress={this.goBack}
              style={isAndroid ? { marginLeft: 14 } : {}}
            >
              <BackImage />
            </TouchableOpacity>
          );
        }}
        renderRight={() => {
          return null;
        }}
      />
    );
  }

  goBack = () => {
    const { data } = this.state;
    // 提醒后端更改二维码
    api.repair.repairFailVerification({ maintenancelNo: data[1] }).then(res => {

    });
    msg.emit('router: goToNext', {
      routeName: 'Main',
    });
  }

  // 提交按钮
  submitBtn = () => {
    const { writeOffAmount, remark, fileList, repairStations, data, veriCardDetails } = this.state;
    const stations = repairStations.length > 0 ? repairStations[0] : {};
    if (Number(writeOffAmount) <= 0) {
      msg.emit('app:tip', { text: '请输入核销金额' });
      return;
    }
    if (!fileList.length) {
      msg.emit('app:tip', { text: '请上传维修凭证' });
      return;
    }
    let newFileList = [];
    fileList.map((item, index) => {
      const file = item.url;
      newFileList.push(file);
    });
    NativeModules.WindowModule.showWindow({
      title: '',
      leftStr: '返回',
      rightStr: '确认核销',
      content: `核销金额：${writeOffAmount}元`,
    }, e => {
      if (e == 1) {
        const params = {
          remarks: remark, // 备注
          writeOffAmount, // 核销金额
          repairId: stations.id, // 修理点id
          repairName: stations.name, // 修理点名称
          accountCarownerId: veriCardDetails.accountCarownerId,
          files: newFileList, // 维修凭证
          id: data[0], // 二位码带过来的id
          maintenancelNo: data[1], // 二维码维修单号单号
          time: data[2], // 二维码带过来的time
        };
        api.repair.repairVerification(params).then(res => {
          if (res.success) {
            msg.emit('router: goToNext', {
              routeName: 'WriteOffResult',
              result: 1
            });
          } else {
            if (res.code == '10010') {
              msg.emit('app:messageBox', {
                isVisible: true,
                title: '余额不足，请核实后在输入核销金额',
                text: '',
                okText: '我知道了',
                isClickBg: false,
                okFn: () => {
                },
              });
            } else {
              msg.emit('app:tip', { text: res.msg });
              msg.emit('router: goToNext', {
                routeName: 'WriteOffResult',
                result: 0
              });
            }
          }
        });
      }
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  headTitleText: {
    color: '#000',
    fontSize: 18,
    fontWeight: isAndroid ? '400' : 'bold',
  },
  headRight: {
    maxWidth: px2dp(250),
    flexDirection: 'row',
    alignItems: 'center',
  },
  headRightImage: {
    width: px2dp(32),
    height: px2dp(32),
    marginRight: px2dp(10)
  },
  headRightText: {
    fontSize: px2dp(28),
    color: fontColorBlack,
    // textAlign: 'right',
    paddingRight: px2dp(40 * 2)
  },
  writeOffContainer: {
    backgroundColor: mainBgColorWhite,
    borderRadius: px2dp(24),
    marginTop: px2dp(24),
    marginHorizontal: px2dp(20),
  },
  oilCardContainer: {
    // marginBottom: 10
  },
  oilTabContainer: {
    height: px2dp(100),
    justifyContent: 'space-around',
    paddingHorizontal: px2dp(15)
  },
  oilTabText: {
    color: '#E6D6BB',
    fontSize: px2dp(24)
  },
  writeOffHandleView: {
    flex: 1,
    marginTop: px2dp(155),
    justifyContent: 'space-around',
    paddingVertical: px2dp(50)
  },
  writeOffHandleContainer: {
    height: px2dp(200),
    justifyContent: 'space-between',
    padding: px2dp(24),
    paddingBottom: px2dp(32),
    borderRadius: px2dp(16)
  },
  writeOffHandleTitle: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  repairEvidence: {
    paddingLeft: px2dp(24),
    paddingTop: px2dp(24),
    flexDirection: 'row',
    alignItems: 'center'
  },
  writeOffHandleImage: {
    width: px2dp(40),
    height: px2dp(40),
    marginRight: px2dp(10)
  },
  defineBtn: {
    width: px2dp(640),
    height: px2dp(88),
    backgroundColor: fontColorCoffee,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: px2dp(12)
  },
  defineBtnTest: {
    color: mainBgColorWhite,
    fontSize: px2dp(32)
  },
  tipsContainer: {
    height: px2dp(200),
    justifyContent: 'center',
    borderTopWidth: px2dp(2),
    borderTopColor: splitLineColorLightGray,
    marginHorizontal: px2dp(20)
  },
  tipsFlag: {
    width: px2dp(6),
    height: px2dp(24),
    marginRight: px2dp(10)
  },
  tipsTitle: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  tipsTitleText: {
    fontSize: px2dp(28),
    color: fontColorBlack,
    fontWeight: 'bold'
  },
  tipsText: {
    color: '#686764',
    fontSize: px2dp(28),
  },
  priceInput: {
    width: '100%',
    fontSize: px2dp(48),
    padding: 0,
    color: fontColorBlack,
    alignItems: 'center',
    marginLeft: px2dp(16)
  },
  inputContent: {
    padding: px2dp(24),
    borderRadius: px2dp(8),
  },
  inputContentTextInput: {
    flex: 1,
    fontSize: px2dp(26),
    height: px2dp(110),
    borderRadius: px2dp(8),
    textAlignVertical: 'top',
    alignItems: 'flex-start',
    justifyContent: 'flex-start',
    color: fontColorBlack
  },
  uploadBox: {
    flexDirection: 'row',
    alignItems: 'center',
    alignItems: 'flex-end',
    paddingLeft: px2dp(24),
    paddingBottom: px2dp(24),
    marginTop: px2dp(32),
  },
  remark: {
    color: '#666562',
    fontSize: px2dp(26),
    paddingTop: px2dp(20)
  },
  btnBox: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'flex-end',
    paddingBottom: px2dp(80)
  },
  boxStyle: {
    width: '90%',
    height: px2dp(96),
    borderRadius: px2dp(8),
    marginTop: px2dp(96)
  },
  textInputContainer: {
    flex: 1,
    // height: px2dp(88),
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    borderRadius: px2dp(12),
    paddingHorizontal: px2dp(10)
  },
});
